package org.aeon.client.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.aeon.client.context.GlobalContext;

/**
 * @author: MissingAeon
 * @date: 2024/1/26 13:14
 * @description:
 */
@Slf4j
@ChannelHandler.Sharable
public class ClientChannelInboundHandler extends ChannelInboundHandlerAdapter {


    public ClientChannelInboundHandler() {
    }

    // 连接事件
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    // 读事件
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.fireChannelRead(msg);
    }

    // 在连接断开时触发
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        windowDisposal();
        log.debug("主动-连接已经断开，按任意键退出..");
    }


    // 在出现异常时触发
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        windowDisposal();
        log.debug("异常-连接已经断开，按任意键退出..{}", cause.getMessage());
    }

    private void windowDisposal() {
        GlobalContext.getContext().getThreadPool().execute(() -> {
            // SwingUtilities.invokeLater(() -> {
            //     // 关闭窗口
            //     accountUI.dispose();
            //     final JFrame mainUI = GlobalContext.getContext().getMainUI();
            //     if (mainUI != null)
            //         mainUI.dispose();
            //     log.debug("窗口关闭完成...");
            // })
        });
    }
}


